package com.tesco.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tesco.entity.domin.YgGoods;
import com.tesco.entity.domin.YgOrder;
import com.tesco.entity.domin.YgUser;
import com.tesco.entity.vo.BusinessOrderVo;
import com.tesco.entity.vo.DeliveryOrderVo;
import com.tesco.entity.vo.UserOrderVo;
import com.tesco.service.YgGoodsService;
import com.tesco.service.YgOrderService;
import com.tesco.service.YgUserService;
import com.tesco.utils.ConstantUtils;
import com.tesco.utils.TokenUtils;
import com.tesco.utils.WebApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "订单模块")
@RequestMapping("/ygorder")
@RestController
@CrossOrigin(origins = "*")
public class OrderController {

    @Autowired
    private YgOrderService ygOrderService;

    @Autowired
    private YgUserService ygUserService;

    @Autowired
    private YgGoodsService ygGoodsService;

    @PostMapping("/addOrderForGoods")
    @ApiOperation("用户下单(token)")
    public WebApiResult orderForGoods(HttpServletRequest request,@ApiParam(name = "订单id",value = "ddid")@RequestParam("spid") Integer spid){
        try {
            String username = TokenUtils.getUsername(request);
            YgUser ygUser = ygUserService.userInfo(username);
            YgGoods ygGoods = ygGoodsService.goodInfo(spid);
            if (!ygGoodsService.subtractGoodNum(1,spid)) {
                return WebApiResult.error("库存不足");
            }
            if (ygUser.getBalance().compareTo(ygGoods.getPrice())<0){
                return WebApiResult.error("余额不足，请充值");
            }
            ygOrderService.addOrderForGood(username, spid);
            UpdateWrapper<YgUser> ygUserUpdateWrapper = new UpdateWrapper<>();
            ygUserUpdateWrapper.set(YgUser.COL_BALANCE,ygUser.getBalance().subtract(ygGoods.getPrice()))
                    .eq(YgUser.COL_USERNAME,username);
            return WebApiResult.ok("下单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebApiResult.error("下单失败");
        }
    }

    @PostMapping("/cancelAnOrder")
    @ApiOperation("用户取消订单(token)")
    public WebApiResult cancelAnOrder(HttpServletRequest request,@ApiParam(name = "订单id",value = "ddid")@RequestParam("ddid") Integer ddid){
        try {
            String username = TokenUtils.getUsername(request);
            YgOrder orderInfo = ygOrderService.getOrderInfo(ddid);
            if (ConstantUtils.OrderStatus1.equals(orderInfo.getSjwc())) {
                int spid = orderInfo.getSpid();
                YgGoods ygGoods = ygGoodsService.goodInfo(spid);
                YgUser ygUser = ygUserService.userInfo(username);
                UpdateWrapper<YgUser> ygUserUpdateWrapper = new UpdateWrapper<>();
                ygUserUpdateWrapper.set(YgUser.COL_BALANCE,ygUser.getBalance().add(ygGoods.getPrice()))
                .eq(YgUser.COL_USERNAME,username);
                ygUserService.update(ygUserUpdateWrapper);
                ygGoodsService.addGoodNum(1,spid);
                ygOrderService.removeById(ddid);
                return WebApiResult.error("取消成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebApiResult.error("商家已接单，取消失败");
    }


    @PostMapping("/orderForGoodsList")
    @ApiOperation("用户下单记录(token)")
    public WebApiResult<List<UserOrderVo>> orderForGoodsList(HttpServletRequest request){
        try {
            String username = TokenUtils.getUsername(request);
            List<YgOrder> ygOrders = ygOrderService.userGoodList(username);
            List<UserOrderVo> orderListVos = new ArrayList<>();
            if (ygOrders.size()>0) {
                for (YgOrder ygOrder : ygOrders) {
                    int spid = ygOrder.getSpid();
                    YgGoods ygGoods = ygGoodsService.goodInfo(spid);
                    UserOrderVo orderListVo = new UserOrderVo();
                    YgUser ygUser2 = ygUserService.userInfo(username);
                    orderListVo.setAddress(ygUser2.getAddress());
                    BeanUtils.copyProperties(ygOrder,orderListVo);
                    BeanUtils.copyProperties(ygGoods,orderListVo);
                    YgUser ygUser = ygUserService.userInfo(ygGoods.getSjname());
                    if (ygOrder.getShyname() != null){
                        YgUser ygUser1 = ygUserService.userInfo(ygOrder.getShyname());
                        orderListVo.setShyhsjc(ygUser1.getHsjc());
                    }
                    orderListVo.setSjhsjc(ygUser.getHsjc());
                    orderListVos.add(orderListVo);
                }
            }
            return WebApiResult.ok(orderListVos);
        } catch (Exception e) {
            e.printStackTrace();
            return WebApiResult.error("查看下单列表失败");
        }
    }


    @PostMapping("/businessOrderReceiving")
    @ApiOperation("商家接单")
    public WebApiResult businessOrderReceiving(@ApiParam(name = "订单id",value = "ddid")@RequestParam("ddid") int ddid){
        try {
            UpdateWrapper<YgOrder> ygOrderUpdateWrapper = new UpdateWrapper<>();
            ygOrderUpdateWrapper.set(YgOrder.COL_SJWC,ConstantUtils.OrderStatus2)
                    .eq(YgOrder.COL_DDID,ddid);
            ygOrderService.update(ygOrderUpdateWrapper);
            return WebApiResult.ok("接单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebApiResult.ok("接单异常");
        }
    }

    @PostMapping("/businessFinishOrderReceiving")
    @ApiOperation("商家完成订单")
    public WebApiResult businessFinishOrderReceiving(@ApiParam(name = "订单id",value = "ddid")@RequestParam("ddid") int ddid){
        try {
            UpdateWrapper<YgOrder> ygOrderUpdateWrapper = new UpdateWrapper<>();
            ygOrderUpdateWrapper.set(YgOrder.COL_SJWC,ConstantUtils.OrderStatus3)
                    .set(YgOrder.COL_SJWCDATE,new Date())
                    .eq(YgOrder.COL_DDID,ddid);
            ygOrderService.update(ygOrderUpdateWrapper);
            return WebApiResult.ok("接单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebApiResult.ok("接单异常");
        }
    }

    @PostMapping("/businessOrderRefund")
    @ApiOperation("商家退单")
    public WebApiResult businessOrderRefund(@ApiParam(name = "订单id",value = "ddid")@RequestParam("ddid") int ddid){
        try {
            ygOrderService.removeById(ddid);
            YgOrder orderInfo = ygOrderService.getOrderInfo(ddid);
            String username = orderInfo.getUsername();
            int spid = orderInfo.getSpid();
            YgGoods ygGoods = ygGoodsService.goodInfo(spid);
            YgUser ygUser = ygUserService.userInfo(username);
            UpdateWrapper<YgUser> ygUserUpdateWrapper = new UpdateWrapper<>();
            ygUserUpdateWrapper.set(YgUser.COL_BALANCE,ygUser.getBalance().add(ygGoods.getPrice()))
                    .eq(YgUser.COL_USERNAME,username);
            ygUserService.update(ygUserUpdateWrapper);
            ygGoodsService.addGoodNum(1,spid);
            ygOrderService.removeById(ddid);
            return WebApiResult.ok("退单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebApiResult.ok("退单异常");
        }
    }

    @PostMapping("/businessOrderList")
    @ApiOperation("商家订单列表(token)")
    public WebApiResult<List<BusinessOrderVo>> businessOrderList(HttpServletRequest request){
        try {
            String username = TokenUtils.getUsername(request);
            List<YgOrder> ygOrders = ygOrderService.businessGoodList(username);
            List<BusinessOrderVo> businessOrderVos = new ArrayList<>();
            for (YgOrder ygOrder : ygOrders) {
                BusinessOrderVo businessOrderVo = new BusinessOrderVo();
                YgUser ygUser = ygUserService.userInfo(ygOrder.getUsername());
                YgGoods ygGoods = ygGoodsService.goodInfo(ygOrder.getSpid());
                if (StringUtils.isNotBlank(ygOrder.getShyname())){
                    YgUser ygUser1 = ygUserService.userInfo(ygOrder.getShyname());
                    businessOrderVo.setShyhsjc(ygUser1.getHsjc());
                }
                BeanUtils.copyProperties(ygUser,businessOrderVo);
                BeanUtils.copyProperties(ygOrder,businessOrderVo);
                businessOrderVo.setSpname(ygGoods.getSpname());
                businessOrderVo.setUserhsjc(ygUser.getHsjc());
                businessOrderVos.add(businessOrderVo);
            }
            return WebApiResult.ok(businessOrderVos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebApiResult.error("查询异常");
    }


    @PostMapping("/deliveryFinishOrder")
    @ApiOperation("配送完成")
    public WebApiResult deliveryFinishOrder(@RequestParam("ddid") int ddid){
        try {
            UpdateWrapper<YgOrder> ygOrderUpdateWrapper = new UpdateWrapper<>();
            ygOrderUpdateWrapper.set(YgOrder.COL_ISDELIVER,ConstantUtils.OrderStatus6)
                    .set(YgOrder.COL_SDDATE,new Date())
                    .eq(YgOrder.COL_DDID,ddid);
            ygOrderService.update(ygOrderUpdateWrapper);
            return WebApiResult.ok("配送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebApiResult.error("配送异常");
    }

    @PostMapping("/deliveryOrderReceiving")
    @ApiOperation("外卖员完成接单")
    public WebApiResult deliveryOrderReceiving(@RequestParam("ddid") int ddid){
        try {
            UpdateWrapper<YgOrder> ygOrderUpdateWrapper = new UpdateWrapper<>();
            ygOrderUpdateWrapper.set(YgOrder.COL_SHYNAME,ConstantUtils.OrderStatus5)
                    .eq(YgOrder.COL_DDID,ddid);
            ygOrderService.update(ygOrderUpdateWrapper);
            return WebApiResult.ok("接单成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebApiResult.error("接单异常");
    }

    @PostMapping("/deliveryOrderList")
    @ApiOperation("配送员订单列表(token)")
    public WebApiResult<List<DeliveryOrderVo>> deliveryOrderList(HttpServletRequest request){
        try {
            String username = TokenUtils.getUsername(request);
            List<YgOrder> ygOrders = ygOrderService.deliveryGoodList(username);
            List<DeliveryOrderVo> deliveryOrderVos = new ArrayList<>();
            for (YgOrder ygOrder : ygOrders) {
                DeliveryOrderVo deliveryOrderVo = new DeliveryOrderVo();
                YgUser ygUser = ygUserService.userInfo(ygOrder.getUsername());
                YgGoods ygGoods = ygGoodsService.goodInfo(ygOrder.getSpid());
                YgUser ygUser1 = ygUserService.userInfo(ygGoods.getSjname());
                BeanUtils.copyProperties(ygGoods,deliveryOrderVo);
                BeanUtils.copyProperties(ygUser,deliveryOrderVo);
                BeanUtils.copyProperties(ygOrder,deliveryOrderVo);
                deliveryOrderVo.setUserhsjc(ygUser.getHsjc());
                deliveryOrderVo.setSjname(ygUser1.getUsername());
                deliveryOrderVo.setSjhsjc(ygUser1.getHsjc());
                deliveryOrderVos.add(deliveryOrderVo);
            }
            return WebApiResult.ok(deliveryOrderVos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebApiResult.error("查询异常");
    }




}
